package org.dromara.business.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.business.domain.Advertising;
import org.dromara.business.domain.BusinessInformation;
import org.dromara.business.domain.User;
import org.dromara.business.domain.bo.UserAgent;
import org.dromara.business.domain.bo.UserBo;
import org.dromara.business.domain.vo.BusinessInformationVo;
import org.dromara.business.domain.vo.UserVo;
import org.dromara.business.service.AdvertisingService;
import org.dromara.business.service.BusinessInformationService;
import org.dromara.business.service.UserService;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.translation.annotation.Translation;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;

import java.util.Date;

import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 用户信息
 *
 * @author zlj
 * @date 2024-11-19
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/user")
public class UserController extends BaseController {
    private final BusinessInformationService businessInformationService;
    private final UserService UserService;
    private final AdvertisingService advertisingService;

    /**
     * 查询用户信息列表
     */
    //@SaCheckPermission("business:user:list")
    @GetMapping("/list")
    public TableDataInfo<UserVo> list(UserBo bo, PageQuery pageQuery) {
        bo.setUserType("xcx_user");
        return UserService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询审核列表
     */
    @GetMapping("/getApprovalList")
    public TableDataInfo<UserVo> getApprovalList(UserBo bo, PageQuery pageQuery) {
        bo.setUserType("xcx_user");
        return UserService.getApprovalList(bo, pageQuery);
    }

    /**
     * 导出用户信息列表
     */
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(UserBo bo, HttpServletResponse response) {
        List<UserVo> list = UserService.queryList(bo);
        ExcelUtil.exportExcel(list, "用户信息", UserVo.class, response);
    }

    /**
     * 获取用户信息详细信息
     *
     * @param userId 主键
     */
    //@SaCheckPermission("business:user:query")
    @GetMapping("/{userId}")
    public R<UserVo> getInfo(@NotNull(message = "主键不能为空")
                             @PathVariable Long userId) {
        return R.ok(UserService.queryById(userId));
    }

    /**
     * 新增用户信息
     */
    // @SaCheckPermission("business:user:add")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@RequestBody UserBo bo) {
        return toAjax(UserService.insertByBo(bo));
    }

    /**
     * 修改用户信息
     */
    //@SaCheckPermission("business:user:edit")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@RequestBody UserBo bo) {
        return toAjax(UserService.updateByBo(bo));
    }

    /**
     * 实名认证审批
     *
     * @param bo
     * @return
     */
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/verifyIdentityApproval")
    public R<Void> verifyIdentityApproval(@RequestBody UserBo bo) {
        return toAjax(UserService.verifyIdentityApproval(bo));
    }

    /**
     * 代理审批
     *
     * @param bo
     * @return
     */
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/proxyApproval")
    public R<Void> proxyApproval(@RequestBody UserBo bo) {
        return toAjax(UserService.proxyApproval(bo));
    }


    /**
     * 代理审批
     *
     * @param bo
     * @return
     */
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/upbateUserVip")
    public R<Void> upbateUserVip(@RequestBody UserBo bo) {
        return toAjax(UserService.upbateUserVip(bo));
    }

    /**
     * 删除用户信息
     *
     * @param userIds 主键串
     */
    //@SaCheckPermission("business:user:remove")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] userIds) {
        return toAjax(UserService.deleteWithValidByIds(List.of(userIds), true));
    }


    /**
     * 判断当前用户是否会员
     */
    //@SaCheckPermission("business:user:query")
    @GetMapping("/ifMember")
    public R<Boolean> ifMember() {
        Long userId = LoginHelper.getUserId();
        User user = UserService.getById(userId);
        if (user != null) {
            if (user.getHyNumber() > 0 && DateUtil.compare(new Date(), user.getGqTime()) <= 0) {
                return R.ok(true);
            }
        }
        return R.ok(false);
    }

    /**
     * 查看手机号
     */
    //@SaCheckPermission("business:user:query")
    @GetMapping("/viewPhone")
    public R<String> viewPhone(String iId) {
        Long userId = LoginHelper.getUserId();
        User user = UserService.getById(userId);
        BusinessInformation information = businessInformationService.getById(iId);

        if (user != null) {
            if (user.getHyNumber() > 0 && DateUtil.compare(new Date(), user.getGqTime()) <= 0) {
                UserService.updateById(new User() {{
                    setUserId(userId);
                    setHyNumber(user.getHyNumber() - 1);
                }});
                if (!"".equals(information.getLxrDh()) && information.getLxrDh() != null) {
                    return R.data(information.getLxrDh());
                }
            }
        }
        return R.fail("查看次数用尽或会员已过期");
    }

    @GetMapping("/getMyInfo")
    public R<UserVo> getMyInfo() {
        User user = UserService.getById(LoginHelper.getUserId());
        if (user != null) {
            // 如果是代理查询
            if ("1".equals(user.getIsProxy()) && null != user.getProxyRegion()) {
                Long count = UserService.lambdaQuery().eq(User::getCity, user.getProxyRegion()).eq(User::getIfCardReview, "2").count();
                user.setRealNumber(count);
                Long advertisementsNumber = advertisingService.lambdaQuery().eq(Advertising::getCity, user.getProxyRegion()).eq(Advertising::getState, 1).count();
                user.setAdvertisementsNumber(advertisementsNumber);
                Long releaseNumber = businessInformationService.lambdaQuery().eq(BusinessInformation::getCity, user.getProxyRegion()).eq(BusinessInformation::getShzt, 1).count();
                user.setReleaseNumber(releaseNumber);
            }
        }
        return R.ok(BeanUtil.toBean(user, UserVo.class));
    }


    /**
     * 实名认证
     *
     * @param bo
     * @return
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/authentication")
    public R<Void> authentication(@RequestBody UserBo bo) {
        return toAjax(UserService.authentication(bo));
    }


    /**
     * 成为代理
     *
     * @param bo
     * @return
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/becomeAgent")
    public R<Void> becomeAgent(@RequestBody UserBo bo) {
        return toAjax(UserService.becomeAgent(bo));
    }


    /**
     * 代理作废
     *
     * @param bo
     * @return
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/proxyInvalidation")
    public R<Void> proxyInvalidation(@RequestBody UserBo bo) {
        return toAjax(UserService.proxyInvalidation(bo));
    }

    /**
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/agentUserList")
    public TableDataInfo<UserVo> agentUserList(UserBo bo, PageQuery pageQuery) {
        return UserService.agentUserList(bo, pageQuery);
    }

    /**
     * 积分兑换
     */
    @GetMapping("/redeem")
    public R<Void> redeem(Integer pointsNumber ) {
      int updateResult=  UserService.redeem(pointsNumber);
        if (updateResult > 0) {
            return R.ok("兑换成功");
        }
        return R.fail("兑换失败");
    }


    /**
     * 获取我的团队
     */
    @GetMapping("/getMyTeam")
    public TableDataInfo<UserVo> getMyTeam(UserBo bo, PageQuery pageQuery ) {

        return  UserService.getMyTeam(bo, pageQuery);

    }
}
